﻿using System.Web.Mvc;
using Api.Common;
using AppManager.Model;
using AppManager.IBLL;

namespace AppManager.Background
{
    /// <summary>
    ///     管理用户的登录
    /// </summary>
    [NoNeedLogin]
    public class AccountController : BaseController
    {
        IUserService userService;
        public AccountController(IUserService userServ)
        {
            userService = userServ;
        }
        public ActionResult Login(string returnUrl)
        {
            if (Th.IsLogin)
            {
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    //這裡注意一個坑 response.redirect("http://www.baidu.com")這種絕對地址redirect是沒有問題的,但是我傳入的returnurl參數是使用urlencode編碼過的,所以必須解碼,否則redirect中無法匹配到http://就會以為是普通字符串直接拼接了
                    Response.Redirect(Server.UrlDecode(returnUrl));
                    return View();
                }
                return Redirect("~/");
            }
            return View();
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Login([Bind(Include = "LoginName,LoginPwd")] Sys_User user, string returnUrl)
        {
            ModelState.Remove("Name");
            if (!ModelState.IsValid || user == null)
            {
                ModelState.AddModelError("LoginError", "參數錯誤");
                return View(user);
            }

            var model = userService.GetModel(s => s.LoginName == user.LoginName);
            if (model == null)
            {
                ModelState.AddModelError("LoginError", "用戶不存在");
                return View(user);
            }

            if (model.LoginPwd == user.LoginPwd)
            {
                CookieHelper.SetLoginCookie(model.Id);
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(Server.UrlDecode(returnUrl));
                }
                return Redirect("~/");
            }
            ModelState.AddModelError("LoginError", "密碼錯誤");
            return View(user);
        }

        public ActionResult LogOut()
        {
            CookieHelper.RemoveLoginCookie();
            return RedirectToAction("Login", "Account");
        }
    }
}